// optimization.js
Page({
  data: {
    subscriptions: [],
    usageData: [],
    analysisData: [],
    loading: false,
    analysisResult: null,
    analysisResultList: [],
    showDetail: false,
    selectedItem: null
  },

  onLoad() {
    this.loadData()
  },

  onShow() {
    this.loadData()
  },

  // 加载数据
  loadData() {
    const subscriptions = wx.getStorageSync('subscriptions') || []
    this.setData({
      subscriptions: subscriptions
    })
    this.generateAnalysisData()
  },

  // 生成分析数据
  generateAnalysisData() {
    const subscriptions = this.data.subscriptions
    const analysisData = subscriptions.map(item => {
      // 从使用分析数据获取使用频率
      const usageKey = 'usage_' + item.id
      let usageRate = Math.floor(Math.random() * 100)
      let usageDays = Math.floor(usageRate / 100 * 30)
      
      // 尝试从使用分析页面获取数据
      const allUsageData = wx.getStorageSync('usageData') || []
      const usageItem = allUsageData.find(u => u.id === item.id)
      if (usageItem) {
        usageRate = usageItem.usageRate || usageRate
        usageDays = usageItem.usageDays || usageDays
      }

      // 计算月度成本
      const monthlyCost = item.cycle === 'year' ? item.price / 12 : item.price
      
      // 计算性价比
      const valueScore = usageRate / monthlyCost
      
      // 判断优化建议类型
      let suggestionType = 'keep' // keep, downgrade, cancel
      let suggestionReason = ''
      
      if (usageRate < 20 && monthlyCost > 10) {
        suggestionType = 'cancel'
        suggestionReason = '使用频率极低且成本较高'
      } else if (usageRate < 40 && monthlyCost > 20) {
        suggestionType = 'downgrade'
        suggestionReason = '使用频率较低，可考虑降级'
      } else if (usageRate >= 70 && valueScore > 5) {
        suggestionType = 'keep'
        suggestionReason = '使用频率高，性价比优秀'
      } else {
        suggestionType = 'keep'
        suggestionReason = '使用情况正常'
      }

      return {
        id: item.id,
        name: item.name,
        price: item.price,
        monthlyCost: monthlyCost,
        monthlyCostText: '¥' + monthlyCost.toFixed(2),
        cycle: item.cycle,
        category: item.category,
        usageRate: usageRate,
        usageDays: usageDays,
        valueScore: valueScore,
        valueScoreText: valueScore.toFixed(2),
        suggestionType: suggestionType,
        suggestionReason: suggestionReason,
        suggestionColor: this.getSuggestionColor(suggestionType),
        suggestionText: this.getSuggestionText(suggestionType)
      }
    })

    // 按建议优先级排序（取消 > 降级 > 保留）
    analysisData.sort((a, b) => {
      const priority = { cancel: 0, downgrade: 1, keep: 2 }
      return priority[a.suggestionType] - priority[b.suggestionType]
    })

    this.setData({
      analysisData: analysisData,
      usageData: analysisData
    })
  },

  // 获取建议颜色
  getSuggestionColor(type) {
    const colors = {
      cancel: '#EF4444',
      downgrade: '#F59E0B',
      keep: '#10B981'
    }
    return colors[type] || '#6B7280'
  },

  // 获取建议文本
  getSuggestionText(type) {
    const texts = {
      cancel: '建议取消',
      downgrade: '建议降级',
      keep: '建议保留'
    }
    return texts[type] || '未知'
  },

  // 调用 AI 分析
  analyzeWithAI() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    const analysisData = this.data.analysisData
    const prompt = this.buildAnalysisPrompt(analysisData)
    
    this.callDeepSeekAPI(prompt).then(result => {
      const resultList = this.formatAnalysisResult(result)
      this.setData({
        analysisResult: result,
        analysisResultList: resultList,
        loading: false
      })
    }).catch(error => {
      console.error('分析失败:', error)
      wx.showToast({
        title: '分析失败，请重试',
        icon: 'none'
      })
      this.setData({ loading: false })
    })
  },

  // 构建分析提示词
  buildAnalysisPrompt(analysisData) {
    let prompt = '请分析以下订阅服务的使用情况，给出具体的优化建议：\n\n'
    
    analysisData.forEach((item, index) => {
      prompt += index + 1 + '. ' + item.name + '\n'
      prompt += '   月度成本：¥' + item.monthlyCost.toFixed(2) + '\n'
      prompt += '   使用频率：' + item.usageRate + '%\n'
      prompt += '   过去30天使用：' + item.usageDays + '天\n'
      prompt += '   性价比评分：' + item.valueScore.toFixed(2) + '\n'
      prompt += '   当前建议：' + item.suggestionText + '\n\n'
    })
    
    prompt += '请从以下角度给出详细建议：\n'
    prompt += '1. 哪些服务应该取消，为什么\n'
    prompt += '2. 哪些服务可以降级到更便宜的方案\n'
    prompt += '3. 哪些服务值得保留，为什么\n'
    prompt += '4. 给出具体的优化方案和预期节省金额\n'
    prompt += '回答要求：\n'
    prompt += '- 不要使用星号、井号等特殊符号\n'
    prompt += '- 使用换行来分段，每个建议单独一段\n'
    prompt += '- 回答要具体实用，控制在300字以内\n'
    
    return prompt
  },

  // 调用 DeepSeek API
  callDeepSeekAPI(prompt) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://api.deepseek.com/v1/chat/completions',
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer sk-68587461c88d4e1ab52f51fde28805ae'
        },
        data: {
          model: 'deepseek-chat',
          messages: [
            {
              role: 'user',
              content: prompt
            }
          ],
          temperature: 0.7,
          max_tokens: 800
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.choices && res.data.choices.length > 0) {
            const content = res.data.choices[0].message.content
            resolve(content)
          } else {
            reject(new Error('API 返回数据格式错误'))
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },

  // 格式化分析结果
  formatAnalysisResult(content) {
    // 移除特殊符号
    content = content.replace(/[*#]/g, '')
    // 按换行分割，过滤空行
    const lines = content.split('\n').filter(line => line.trim().length > 0)
    return lines
  },

  // 查看详情
  showDetail(e) {
    const index = e.currentTarget.dataset.index
    const item = this.data.analysisData[index]
    this.setData({
      showDetail: true,
      selectedItem: item
    })
  },

  // 关闭详情
  closeDetail() {
    this.setData({
      showDetail: false,
      selectedItem: null
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  }
})
